from django.db import models
from utils.models import CoreModel, table_prefix
import base64
from system.settings.utils import AppSetting
from libs.utils import AttrDict
from utils.ssh import SSH


class Project(CoreModel):
    name_en = models.CharField(max_length=32, verbose_name='项目英文名')
    name = models.CharField(max_length=32, verbose_name='项目名', unique=True)

    class Meta:
        db_table = table_prefix + 'project'
        verbose_name = '项目信息表'
        verbose_name_plural = verbose_name


class Channel(CoreModel):
    channel_api = models.CharField(max_length=32, verbose_name='渠道简称')
    channel_name = models.CharField(max_length=32, verbose_name='渠道中文名字')
    db_user = models.CharField(max_length=32, verbose_name='渠道数据库用户名', null=True)
    db_password = models.CharField(max_length=32, verbose_name='渠道数据库密码', null=True)
    db_name = models.CharField(max_length=32, verbose_name='渠道数据库名', null=True)
    host_ip = models.CharField(max_length=32, verbose_name='渠道OPS主机IP', null=True)
    db_port = models.IntegerField(verbose_name='渠道数据库端口', null=True)
    ssh_port = models.IntegerField(verbose_name='SSH端口', null=True)
    corp_id = models.CharField(max_length=64, verbose_name='企业ID', null=True)
    agent_id = models.CharField(max_length=64, verbose_name='应用ID', null=True)
    secret = models.CharField(max_length=64, verbose_name='应用secret', null=True)
    language = models.CharField(max_length=64, verbose_name='语言', null=True)
    project = models.ForeignKey(to='Project', to_field='id', on_delete=models.CASCADE)

    @staticmethod
    def make_password(plain_password):
        return str(base64.b64encode(plain_password.encode(encoding='utf-8')), encoding='utf8')

    def get_password(self):
        return str(base64.b64decode(self.db_password), encoding='utf-8')

    @property
    def we_chat_config(self):
        tmp = AttrDict()
        tmp.corp_id = self.corp_id or AppSetting.get('corp_id')
        tmp.agent_id = self.agent_id or AppSetting.get('agent_id')
        tmp.secret = self.secret or AppSetting.get('secret')
        return tmp

    def get_ssh(self, pkey=None):
        pkey = pkey or AppSetting.get('private_key')
        return SSH(self.host_ip, self.ssh_port, 'root', pkey)

    class Meta:
        db_table = table_prefix + 'channel'
        verbose_name = '渠道信息表'
        verbose_name_plural = verbose_name
